package com.jbit.examSystem.controller;

import com.jbit.examSystem.pojo.EmailCode;
import com.jbit.examSystem.pojo.ResponseResult;
import com.jbit.examSystem.pojo.Student;
import com.jbit.examSystem.pojo.User;
import com.jbit.examSystem.service.StudentService;
import com.jbit.examSystem.service.TeacherService;
import com.jbit.examSystem.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("email")
public class EmailController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;

    @RequestMapping("sendEmail")
    @ResponseBody
    public ResponseResult sendEmail(HttpSession session, String receiveMailAccount) {
        ResponseResult result = null;

        EmailUtil emailUtil = new EmailUtil(receiveMailAccount);
        try {
            EmailCode code = emailUtil.sendEmail();
            session.setAttribute("emailCode", code);
            result = ResponseResult.success(null);
        } catch (Exception e) {
            result = ResponseResult.error(e.getMessage());
        }

        return result;
    }

    @RequestMapping("checkEmail")
    @ResponseBody
    public Map<String, Object> checkEmail(String email, Integer identityId) {
        Map<String, Object> map = new HashMap<>();

        //判断邮箱是否已被注册
        User user = studentService.checkEmail(email);
        if (user != null) {
            map.put("valid", false);
        } else {
            user = teacherService.checkEmail(email);
            if (user != null){
                map.put("valid", false);
            } else {
                map.put("valid", true);
            }
        }
        return map;
}

    @RequestMapping("checkEmailCode")
    @ResponseBody
    public Map<String, Object> checkEmail(String emailCode, HttpSession session) {
        EmailCode code = (EmailCode) session.getAttribute("emailCode");
        Map<String, Object> map = new HashMap<>();

        map.put("valid", true);

        Date date = new Date();
        boolean result = date.before(code.getExpirationTime());
        if (!result || !emailCode.equals(code.getCode())) {
            map.put("valid", false);
        }
        return map;
    }
}
